class Snake{
    // 头
    head: HTMLElement;
    // 身体
    bodies: HTMLCollection;

    // 获取蛇容器
    snakeEl: HTMLElement;
    constructor() {
        this.head = document.querySelector('#snake > div') as HTMLElement;
        this.bodies = document.getElementById('snake')?.getElementsByTagName('div') as HTMLCollection;
        this.snakeEl = document.getElementById('snake') as HTMLElement;
    }

    get X(): number{
        return this.head.offsetLeft;
    }

    get Y(): number{
        return this.head.offsetTop;
    }

    set X(value: number){
        for(let i=this.bodies.length-1;i>0;i--){
            (this.bodies[i] as HTMLElement).style.left = (this.bodies[i-1] as HTMLElement).style.left;
            (this.bodies[i] as HTMLElement).style.top = (this.bodies[i-1] as HTMLElement).style.top;
        }
        // console.log("x",this.bodies);
        this.head.style.left = value + 'px';
    }

    set Y(value: number){
        this.head.style.top = value + 'px';
    }

    addBody() {
        // 想snake容器 添加 div
        const tempDiv = document.createElement('div');
        tempDiv.style.position = "absolute";
        tempDiv.style.left = this.head.style.left;
        tempDiv.style.top = this.head.style.top;

        this.snakeEl.insertAdjacentElement("beforeend", tempDiv );
    }
}
export default Snake;